<?php

namespace app\common\model;
use think\Model;
use think\Facade\Db;
use app\common\model\Member as MemberModel;
use app\common\model\MemberCurrency as MemberCurrencyModel;

class UserMoneyLog extends Model
{
    protected $name = 'user_money_log';

    /**
     * 用户资金变化表
     * @param $mid          用户ID
     * @param $currency     币种名称
     * @param $num          数量
     * @param null $type    来源
     * @param null $relation_id 关联来源id
     * @param $remarks      备注
     * @param $freeze      1:非冻结 2:已冻结
     */
    public static function change($mid,$currency,$num,$type = '',$relation_id='',$remarks = '',$freeze = 1)
    {
        if ($num == 0) return false;
        $wallet = MemberCurrencyModel::member_renew($mid);

        $money = 0;
        $cid = 0;
        //判断余额
        foreach ($wallet['waller'] as $v){
            if($v['name'] == $currency){    //比对币种
                if($freeze == 1 && $num < 0 && $v['money'] < -$num) return false;
                if($freeze == 2 && $num < 0 && $v['freeze_money'] < -$num) return false;
                $money = $freeze == 1 ? $v['money'] : $v['freeze_money'];   //当前余额
                $cid = $v['cid'];
            }
        }

        if ($cid == 0) return false;

        self::startTrans();
        try{

            $data = [
                'mid'   =>  $mid,
                'cid'   =>  $cid,
                'currency'  =>  $currency,
                'num'   =>  $num,
                'before_num'    =>  $money,
                'after_num' =>  bcadd($money,$num,8),
                'type'  =>  $type,
                'relation_id'   =>  $relation_id,
                'status'    =>  $num > 0 ? 1: 2,    //判断是新增还是减少
                'remarks'   =>  $remarks,
                'freeze'    =>  $freeze,    //1:非冻结 2:已冻结
                'add_time'  =>  time()
            ];

            $id = self::insertGetId($data);

            if(empty($id)){
                self::rollback();
                return false;
            }

            $up_ba = MemberCurrencyModel::up_balance($mid,$currency,$num,$freeze);
            if(!$up_ba){
                Db::rollback();
                return false;
            }

            self::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            self::rollback();
            return false;
        }

    }

    /**
     * 资金流
     * @param array $where  查询条件
     * @param int $page 页码
     * @param int $limit    每页数量
     * @param string $order 排序
     * @return array
     * @throws \think\db\exception\DbException
     */
    public static function getApiList($where = [],$page = 1,$limit = 20,$order = 'id desc',$language = 'traditional'){

        $data = self::where($where)->order($order)->field('id,currency,num,type,relation_id,remarks,status,add_time')->paginate(['list_rows'=>$limit,'page'=>$page])->toArray();
        //翻译来源
        foreach ($data['data'] as $k => $v){
            $data['data'][$k]['type_name'] = config('capital')[$v['type']][$language];
            $data['data'][$k]['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
        }

        return $data;
    }

    /**
     * 统计时间内资金流
     * @param string $currency
     * @param int $start
     * @param int $end
     * @param int $mid
     * @return float
     */
    public static function time_statistics($currency = 'usdt',$start = 0,$end = 0,$mid = 0,$type = ''){
        $data = self::where('currency',$currency)->whereTime('add_time','between',[$start,$end]);
        if($mid > 0) $data = $data->where('mid',$mid);
        if(!empty($type)) $data = $data->where('type',$type);
        $data = $data->sum('num');
        return $data;
    }

}